package categories;

import org.apache.log4j.Logger;
import org.supercsv.io.CsvListReader;
import org.supercsv.prefs.CsvPreference;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CategoriesRegistry {
    private final Logger log = Logger.getLogger(CategoriesRegistry.class);

    private Map<Long, CustomerCategory> numberToCategoryIdx;

    public CategoriesRegistry(File from) throws IOException {
        this.numberToCategoryIdx = new HashMap<Long, CustomerCategory>();
        read(from);
    }

    public void read(File file) throws IOException {
        long now = System.currentTimeMillis();

        CsvListReader reader = new CsvListReader(new FileReader(file), new CsvPreference('"', ';', "\r\n"));
        try {
            while (reader.read() != null) {
                Long customerNumber = Long.valueOf(reader.get(0));

                if (log.isTraceEnabled()) {
                    log.trace("read category: " + reader.get(1));
                }

                CustomerCategory cc = CustomerCategory.valueOfAbbrevated(reader.get(1));

                if(numberToCategoryIdx.containsKey(customerNumber) && numberToCategoryIdx.get(customerNumber) != cc) {
                    throw new IllegalArgumentException("File contains duplicated ("+customerNumber+") number with differnet values!");
                }

                numberToCategoryIdx.put(customerNumber, cc);

                if (log.isTraceEnabled()) {
                    log.trace("add this entry: " + customerNumber + " to category: " + cc);
                }
            }
        } finally {
            reader.close();

            log.info("Total " + numberToCategoryIdx.size() + " rows processed from " + file +
                    " in " + (System.currentTimeMillis() - now) + " ms");
        }
    }


    /**
     * @return null if number wasn't registered
     */
    public CustomerCategory getByNumber(long number) {
        CustomerCategory result = numberToCategoryIdx.get(number);
        if(result == null) {
            result = CustomerCategory.Uncategorised;
        }
        return result;
    }


    public static void main(String args[]) throws IOException {
        CategoriesRegistry cat = new CategoriesRegistry(new File("./data/categories.csv"));
    }
}
